<template>
  <div class="admin-container">
    <h2>车位管理</h2>

    <!-- 数据概览 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-value">{{ parkingStats.total }}</div>
          <div class="stats-label">总车位数</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-value success">{{ parkingStats.available }}</div>
          <div class="stats-label">可用车位</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-value warning">{{ parkingStats.used }}</div>
          <div class="stats-label">已使用</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-value info">{{ parkingStats.deleted }}</div>
          <div class="stats-label">已删除</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button-group>
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>新增车位
        </el-button>
        <el-button @click="refreshList">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </el-button-group>

      <el-input
        v-model="searchKeyword"
        placeholder="搜索车位编号/位置"
        class="search-input"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 车位列表 -->
    <el-table 
      :data="filteredParkingList" 
      border 
      v-loading="loading"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="spotNumber" label="车位编号" width="120" />
      <el-table-column prop="location" label="位置" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(row)"
              :disabled="row.isDeleted === 1"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增车位' : '编辑车位'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="车位编号" prop="spotNumber">
          <el-input v-model="form.spotNumber" placeholder="请输入车位编号" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入位置信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { getAllParkingSpots, updateParkingSpot, deleteParkingSpot,createParkingSpot  } from '@/api/adminApi'

// 数据状态
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const parkingList = ref([])

// 表单数据
const form = reactive({
  spotId: '',
  spotNumber: '',
  location: ''
})

// 表单验证规则
const rules = {
  spotNumber: [
    { required: true, message: '请输入车位编号', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入位置信息', trigger: 'blur' }
  ]
}

// 统计数据
const parkingStats = computed(() => {
  const total = parkingList.value.length
  const available = parkingList.value.filter(item => item.status === '可用').length
  const used = parkingList.value.filter(item => item.status === '已占用').length
  const deleted = parkingList.value.filter(item => item.isDeleted === 1).length

  return {
    total,
    available,
    used,
    deleted
  }
})

// 计算属性：过滤后的列表
const filteredParkingList = computed(() => {
  let result = parkingList.value
  
  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(item => 
      item.spotNumber.toLowerCase().includes(keyword) ||
      item.location.toLowerCase().includes(keyword)
    )
  }
  
  // 更新总数
  total.value = result.length
  
  // 分页处理
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  
  return result.slice(startIndex, endIndex)
})

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    '可用': 'success',
    '已占用': 'warning',
    '维护中': 'info'
  }
  return types[status] || 'info'
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  return new Date(timestamp).toLocaleString()
}

// 获取车位列表
const fetchParkingList = async () => {
  loading.value = true
  try {
    const response = await getAllParkingSpots()
    if (response.code === 200) {
      parkingList.value = response.data
      total.value = response.data.length
    }
  } catch (error) {
    ElMessage.error('获取车位列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 显示新增对话框
const showAddDialog = () => {
  dialogType.value = 'add'
  form.spotId = ''
  form.spotNumber = ''
  form.location = ''
  dialogVisible.value = true
}

// 编辑车位
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.spotId = row.spotId
  form.spotNumber = row.spotNumber
  form.location = row.location
  dialogVisible.value = true
}

// 删除车位
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除车位 ${row.spotNumber} 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteParkingSpot(row.spotId)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchParkingList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}
// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response
        if (dialogType.value === 'add') {
          // 新增车位时设置默认状态为可用
          response = await createParkingSpot({
            spotNumber: form.spotNumber,
            location: form.location,
            status: '可用'
          })
        } else {
          response = await updateParkingSpot(form)
        }

        if (response.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
          dialogVisible.value = false
          fetchParkingList()
        }
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '修改失败')
        console.error(error)
      }
    }
  })
}

// 刷新列表
const refreshList = () => {
  fetchParkingList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 初始化
onMounted(() => {
  fetchParkingList()
})
</script>

<style scoped>
.admin-container {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
  padding: 20px;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stats-value.success { color: #67C23A; }
.stats-value.warning { color: #E6A23C; }
.stats-value.info { color: #909399; }

.stats-label {
  color: #606266;
  font-size: 14px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .stats-row .el-col {
    margin-bottom: 10px;
  }

  .operation-bar {
    flex-direction: column;
    gap: 10px;
  }

  .search-input {
    width: 100%;
  }
}
</style>